package cn.core.dict.listener;

import cn.core.dict.eo.Dict;
import cn.core.dict.eo.DictValue;
import cn.core.dict.mapper.DictMapper;
import cn.core.dict.mapper.DictValueMapper;
import cn.core.dict.qo.DictQO;
import cn.core.dict.qo.DictValueQO;
import cn.core.dict.service.intf.IDictService;
import cn.core.tool.event.CoreDataEvent;
import cn.core.tool.exception.CoreException;
import cn.core.tool.util.CoreTool;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Primary;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.LinkedHashMap;

/**
 * 数据字典 事件监听器
 */
@Log4j2
@Primary
@Service
public class DictEventListener {

  @Resource
  private DictMapper dictMapper;

  @Resource
  private DictValueMapper dictValueMapper;

  @Resource
  private IDictService dictService;

  /**
   * 数据字典标识 >>> 数据字典值键值信息
   */
  @EventListener(condition = "#coreDataEvent.eventKey == 'getDictValueMapInfoByDictKey'")
  public void getDictValueMapInfoByDictKey(CoreDataEvent coreDataEvent) throws Exception {
    try {
      if (CoreTool.isNullStr(coreDataEvent.getParam())) {
        throw new CoreException("参数错误，数据字典标识为空！");
      }
      Collection<Dict> rDictSet = dictMapper.query(new DictQO().setDictKey(coreDataEvent.getParam()));
      if (CoreTool.isNotEmpty(rDictSet)) {
        Dict rDict = rDictSet.iterator().next();
        Collection<DictValue> rDictValueSet = dictValueMapper.query(
            new DictValueQO()
                .setFkid(rDict.getId())
                .setWeightOrderAsc("y"));
        if (CoreTool.isNotEmpty(rDictValueSet)) {
          LinkedHashMap<String, String> dictValueMapInfo = new LinkedHashMap<>();
          for (DictValue eo : rDictValueSet) {
            dictValueMapInfo.put(eo.getCodeName(), eo.getDisplayName());
          }
          coreDataEvent.setData(dictValueMapInfo);
        }
      }
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  /**
   * 数据字典 >>> 获取所有数据字典和数据字典值键值信息
   */
  @EventListener(condition = "#coreDataEvent.eventKey == 'getAllDictValueMapInfo'")
  public void getAllDictValueMapInfo(CoreDataEvent coreDataEvent) throws Exception {
    try {
      coreDataEvent.setData(dictService.getAllDictValueMapInfo());
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

}
